跳到主要内容

JZ5 用两个栈实现队列

https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6

解题一

import java.util.Stack;

public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();

public void push(int node) {
stack1.push(node);
}

public int pop() {
//等待 stack2 弹完再从 stack1 重新导入
if(!stack2.isEmpty()) return stack2.pop();

while(!stack1.isEmpty()) stack2.push(stack1.pop());

return stack2.pop();
}
}

23-5-23

耗时 4min

var stack1 [] int
var stack2 [] int

func Push(node int) {
stack1 = append(stack1, node)
}

func Pop() int {
if len(stack1) == 0 {
return 0
}
node := stack1[0]
stack1 = stack1[1:]
return node
}